package com.beaven.model.data;

import android.support.annotation.NonNull;
import com.beaven.model.data.helper.DbHelper;
import com.beaven.model.model.db.BaseDbModel;
import com.raizlabs.android.dbflow.structure.database.transaction.QueryTransaction;
import java.lang.reflect.Type;
import java.util.List;
import net.qiujuer.genius.kit.reflect.Reflector;
import timber.log.Timber;

/**
 * author: Beaven
 * time: 2017/5/24 11:04
 */

public abstract class BaseDbRepository<Data extends BaseDbModel<Data>>
    implements DbDataSource<Data>, DbHelper.ChangedListener<Data>,
    QueryTransaction.QueryResultListCallback<Data> {

  private SuccessCallBack<List<Data>> callBack;

  private Class<Data> dataClass;

  @SuppressWarnings("unchecked") public BaseDbRepository() {
    Type[] types = Reflector.getActualTypeArguments(BaseDbRepository.class, this.getClass());
    dataClass = (Class<Data>) types[0];
  }

  @Override public void load(SuccessCallBack<List<Data>> callBack) {
    this.callBack = callBack;
    DbHelper.instance().addListener(dataClass, this);
  }

  @Override public void dispose() {
    this.callBack = null;
    DbHelper.instance().removeListener(dataClass, this);
  }

  @Override
  public void onListQueryResult(QueryTransaction transaction, @NonNull List<Data> tResult) {
    onDataResult(tResult);
  }

  // 数据库监听
  @SafeVarargs @Override public final void onDataSave(Data... list) {
    Timber.i("数据添加");
    notifyDataChange();
  }

  @SafeVarargs @Override public final void onDataDelete(Data... list) {
    Timber.i("数据删除");
    notifyDataChange();
  }

  // 通知界面刷新的方法
  private void notifyDataChange() {
    Timber.i("数据库数据改变");
    DataSource.SuccessCallBack<List<Data>> callback = this.callBack;
    if (callback != null) {
      callback.notifyData();
    } else {
      Timber.e("callback is null");
    }
  }

  private void onDataResult(List<Data> dataList) {
    Timber.i("数据库数据取出");
    DataSource.SuccessCallBack<List<Data>> callback = this.callBack;
    if (callback != null) {
      callback.loadDataSuccess(dataList);
    } else {
      Timber.e("callback is null");
    }
  }
}
